<template>
  <div class="main">
    <!-- 标题 -->
    <Title :title="title" />
    <el-card>
      <el-row style="margin-bottom: 17px">
        <el-col :span="6">
          <el-input
            v-model="queryParams.keyword"
            placeholder="关键词"
            class="input-with-select"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="queryParams.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="queryParams.mold" placeholder="角色类型">
            <el-option
              v-for="item in roleList"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <div class="search btn" @click="getRoleList">搜索</div>
          <div class="reset btn" @click="resetSearch">重置</div>
        </el-col>
        <!-- <el-col :span="6" /> -->
        <el-col
          :span="9"
          style="display: flex; align-items: center; justify-content: flex-end"
        >
          <div class="add-btn btn" @click="addDialog = true">新增</div>
          <div class="remove-select btn" @click="removeRoles">删除</div>
        </el-col>
      </el-row>
      <BaseTable
        :has-index="true"
        :has-border="true"
        :table-data="tableData"
        :table-data-total="total"
        :table-column-options="tableColumnOptions"
        @tableUpdate="tableUpdate"
        @selectionChange="selectionChange"
      >
        <!-- 类型插槽 -->
        <template #tag="{ data }">
          <div class="tag">
            <el-tag v-if="data.type == 1" type="success">tag1</el-tag>
            <el-tag v-if="data.type == 0" type="danger">tag2</el-tag>
          </div>
        </template>
        <!-- 操作插槽 -->
        <template #operation="{ data }">
          <div
            class="action"
            style="
              display: flex;
              align-items: center;
              justify-content: space-around;
            "
          >
            <!-- <el-link :underline="false">查看 </el-link> -->
            <el-link
              :underline="false"
              @click="changeStatus(data)"
            >{{ data.status === '正常' ? '停用' : '启用' }}
            </el-link>
            <!-- </el-popconfirm> -->
            <el-link :underline="false" @click="removeRole(data.id)">
              删除
            </el-link>
            <el-link
              :underline="false"
              @click="handleEdit(JSON.parse(JSON.stringify(data)))"
            >
              修改
            </el-link>
          </div>
        </template>
      </BaseTable>
    </el-card>
    <!-- 添加角色弹窗 -->
    <el-dialog
      title="角色添加"
      :visible.sync="addDialog"
      width="40%"
      :before-close="handleClose"
      @close="close"
    >
      <div class="box">
        <div class="role-box">
          <div class="lebel">角色类型：</div>
          <div class="role-list">
            <div
              v-for="(item, index) in roleTypeList"
              :key="index"
              class="role-item"
              @click="handleChangeRole(index)"
            >
              <i
                class="icon"
                :class="currentTypeIndex === index ? 'active' : ''"
              />
              <span class="label">{{ item.label }}</span>
              <span v-if="item.desc" class="desc">({{ item.desc }})</span>
            </div>
          </div>
        </div>
        <el-row class="role-name">
          <span>{{
            roleTypeList[currentTypeIndex].label.indexOf('管理员') === -1
              ? roleTypeList[currentTypeIndex].label
              : '角色'
          }}名称：</span>
          <el-input v-model="addForm.name" placeholder="请输入名称" />
        </el-row>
        <template v-if="currentTypeIndex === 2">
          <el-row class="role-name">
            <span>年薪：</span>
            <el-input v-model="addForm.year_salary" placeholder="请输入年薪" />
          </el-row>
          <el-row class="role-name">
            <span>安家费：</span>
            <el-input
              v-model="addForm.settle_down"
              placeholder="请输入安家费"
            />
          </el-row>
          <el-row class="role-name">
            <span>科研启动费：</span>
            <el-input
              v-model="addForm.startup"
              placeholder="请输入科研启动费"
            />
          </el-row>
        </template>
        <el-row class="role-box" style="margin-top: 20px">
          <span style="flex-shrink: 0">角色状态：</span>
          <div class="role-list" style="display: flex; align-items: center">
            <div
              v-for="(item, index) in statusList"
              :key="index"
              style="margin-left: 10px"
              class="role-item"
              @click="handleStatusChoose(index)"
            >
              <i
                class="icon"
                :class="currentStatusIndex === index ? 'active' : ''"
              />
              <span class="label">{{ item.label }}</span>
            </div>
          </div>
        </el-row>
        <el-row
          v-if="currentTypeIndex <= 1"
          class="role-box"
          style="margin-top: 20px"
        >
          <span style="flex-shrink: 0">功能权限：</span>
          <div class="role-list" style="display: flex; align-items: center">
            <div
              v-for="(item, index) in ruleList"
              :key="index"
              class="role-item"
              style="margin-left: 10px"
              @click="handleRuleChoose(index)"
            >
              <i
                class="icon"
                :class="currentRuleIndex === index ? 'active' : ''"
              />
              <span class="label">{{ item.label }}</span>
            </div>
          </div>
        </el-row>
      </div>
      <el-tree
        v-if="currentTypeIndex === 1 && currentRuleIndex === 1"
        ref="tree"
        :props="props"
        :data="ruleTree"
        node-key="id"
        show-checkbox
        :default-checked-keys="defaultChecked"
        @check-change="handleCheckChange"
      />
      <div class="submit-btn" @click="handleSubmit">确认</div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addDialog = false">确 认</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>

<script>
import config from './config'
import BaseTable from '@/components/BaseTable'
import {
  getRoleList,
  getRuleList,
  addRule,
  removeRole,
  editStatus
} from '@/api/role'
export default {
  name: 'App',
  components: {
    BaseTable
  },
  data () {
    return {
      title: '',
      keyword: '',
      value: 1,
      queryParams: {
        keyword: '',
        status: '',
        mold: '',
        page: 1
      },
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '正常',
          value: 0
        },
        {
          label: '停用',
          value: 1
        }
      ],
      tableData: [],
      tableColumnOptions: config.tableColumnOptions,
      // 添加角色弹窗
      addDialog: false,
      // 角色类型数据
      roleTypeList: JSON.parse(JSON.stringify(config.roleTypeList)),
      // 当前选中角色的下标
      currentTypeIndex: 0,
      // 当前选中状态下标
      currentStatusIndex: 0,
      // 当前选中权限类型下标
      currentRuleIndex: 0,
      addForm: {
        // 角色类型
        mold: config.roleTypeList[0].label,
        // 角色名称
        name: '',
        status: 0,
        power: '',
        id: '',
        // 年薪
        year_salary: '',
        // 安家费
        settle_down: '',
        // 科研启动费
        startup: ''
      },
      // 状态列表
      statusList: [
        {
          label: '正常',
          value: 1
        },
        {
          label: '停用',
          value: 0
        }
      ],
      // 权限列表
      ruleList: [
        {
          label: '默认'
        }
      ],
      props: {
        label: 'title',
        children: 'child'
      },
      // 树结构数据
      ruleTree: [],
      // 总条数
      total: 0,
      // 选中的角色id数组
      ids: [],
      // 树结构默认选中
      defaultChecked: [],
      roleList: [
        {
          value: '管理员'
        },
        {
          value: '人才'
        },
        {
          value: '学院'
        },
        {
          value: '专家'
        }
      ]
    }
  },
  created () {
    // 设置标题
    this.title = this.$route.meta.title
    this.getRoleList()
    this.getRuleList()
  },
  methods: {
    // close () {
    //   this.roleTypeList = JSON.parse(JSON.stringify(config.roleTypeList))
    // },
    // 选择框改变时
    selectionChange (e) {
      const ids = []
      e.forEach((item) => {
        ids.push(item.id)
      })
      this.ids = ids
    },
    // 表格页码发生变化时
    tableUpdate (e) {
      this.queryParams.page = e.currentPage
      this.getRoleList()
    },
    tableRowEdit (e) {
      console.log('拿到此行的数据', e)
    },
    tableRowDelete (e) {
      console.log(e)
    },
    // 关闭添加角色弹窗
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.resetAddRole()
          done()
        })
        .catch((_) => {})
    },
    // 角色类型点击事件
    handleChangeRole (index) {
      if (this.currentRuleIndex !== index) {
        this.resetAddRole()
      }
      switch (index) {
        case 0:
          this.ruleList = [
            {
              label: '默认'
            }
          ]
          break
        case 1:
          this.ruleList = [
            {
              label: '默认'
            },
            {
              label: '自定义'
            }
          ]
          break
        default:
          break
      }
      this.currentTypeIndex = index
      this.addForm.mold = this.roleTypeList[index].label
    },
    // 状态选中
    handleStatusChoose (index) {
      this.currentStatusIndex = index
      this.addForm.status = this.statusList[index].value
    },
    // 权限切换
    handleRuleChoose (index) {
      this.currentRuleIndex = index
    },

    // 获取list列表
    async getRoleList () {
      const res = await getRoleList(this.queryParams)
      this.tableData = res.data.data ?? []
      this.total = res.data.total
    },
    // 获取规则列表
    async getRuleList () {
      const res = await getRuleList()
      this.ruleTree = res.data
    },
    // 删除角色
    async removeRoles () {
      await removeRole({ ids: this.ids })
      this.$message.success('删除成功')
      this.getRoleList()
    },
    // 删除单条
    async removeRole (id) {
      await removeRole({ ids: [id] })
      this.$message.success('删除成功')
      this.getRoleList()
    },
    // 获取树节点选中id数组
    getCheckedKeys () {
      this.addForm.power = this.$refs.tree.getCheckedKeys().join(',')
    },
    // 节点选中时触发
    handleCheckChange () {
      this.getCheckedKeys()
    },
    // 重置表单
    resetAddRole () {
      this.addForm = {
        // 角色类型
        mold: config.roleTypeList[0].label,
        // 角色名称
        name: '',
        status: 0,
        power: '',
        id: '',
        // 年薪
        year_salary: '',
        // 安家费
        settle_down: '',
        // 科研启动费
        startup: ''
      }
    },
    // 重置搜索表单
    resetSearch () {
      this.queryParams = {
        keyword: '',
        status: '',
        page: 1
      }
    },
    // 修改角色信息
    handleEdit (data) {
      this.addForm = data
      // 设置角色类型选中
      this.roleTypeList.forEach((item, index) => {
        if (data.mold === item.label) {
          this.currentTypeIndex = index
        }
      })
      // 设置角色状态选中
      this.statusList.forEach((item, index) => {
        if (data.label === data.status) {
          this.currentStatusIndex = index
        }
      })
      switch (this.currentTypeIndex) {
        case 0:
          this.ruleList = [
            {
              label: '默认'
            }
          ]
          break
        case 1:
          this.ruleList = [
            {
              label: '默认'
            },
            {
              label: '自定义'
            }
          ]
          break
        default:
          break
      }
      if (data.power && data.mold !== '超级管理员') {
        this.currentRuleIndex = 1
        this.defaultChecked = data.power.split(',')
      }
      this.addDialog = true
    },
    async changeStatus (data) {
      const status = data.status === '正常' ? 1 : 0
      await editStatus({
        status,
        id: data.id
      })
      this.$message.success('修改成功')
      this.getRoleList()
    },
    // 提交
    async handleSubmit () {
      await addRule(this.addForm)
      this.roleTypeList = JSON.parse(JSON.stringify(config.roleTypeList))
      this.currentTypeIndex = 0
      this.$message.success('添加成功')
      this.resetAddRole()
      this.getRoleList()
      this.addDialog = false
    }
  }
}
</script>

<style lang="scss">
.el-row {
  .el-col {
    &:nth-child(2) {
      margin-left: 16px;
    }
    &:nth-child(3),
    &:nth-child(4) {
      display: flex;
      align-items: center;
      .btn {
        width: 100px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #2860c3;
        border: 1px solid #dcdcdc;
        border-radius: 3px;
        box-sizing: border-box;

        font-size: 16px;
        font-family: MicrosoftYaHei;
        font-weight: 400;
        color: #ffffff;
        cursor: pointer;
        &:nth-last-child(2n + 1) {
          margin-left: 8px;
        }
      }
      .reset {
        background: #f28e02;
      }
    }
  }
}

.role-box {
  display: flex;
  .role-list {
    .role-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      cursor: pointer;

      .icon {
        position: relative;
        display: block;
        width: 18px;
        height: 18px;
        border: 1px solid #eee;
        border-radius: 50%;
        &.active::after {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          content: '';
          display: block;
          width: 10px;
          height: 10px;

          background-color: #2860c3;
          border-radius: 50%;
        }
        &.active {
          border: 1px solid #2860c3;
        }
      }
      .label {
        margin-left: 6px;
      }
      .desc {
        color: #888888;
      }
    }
  }
}
.role-name {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  margin-bottom: 10px;
  span {
    width: 70px;
    flex-shrink: 0;
  }
}

.submit-btn {
  margin: 0 auto;
  margin-top: 20px;
  width: 100%;
  height: 60px;
  text-align: center;
  background: #ef8334;
  border-radius: 5px;
  font-size: 18px;
  font-family: MicrosoftYaHei;
  font-weight: bold;
  color: #ffffff;
  line-height: 60px;
  cursor: pointer;
}
</style>
